<template>
  <div>
    <div v-if="searchStatus" class="box-shadow pad10 mgb10">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <el-row>
          <el-col :span="18">
            <el-form-item label="日期">
              <MyDateTime
                format="YYYY-MM-DD"
                v-model="queryParams.Day"
                type="date"
              ></MyDateTime>
            </el-form-item>
            <el-form-item label="课程">
              <Selector
                v-model="queryParams.Course"
                category="课程级联"
                cascader="级联"
              ></Selector>
            </el-form-item>
            <el-form-item label="教师">
              <Selector
                v-model="queryParams.Teacher"
                category="用户列表"
                :query="{ Type: 2 }"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="flex jend acenter">
            <div class="flex fnw">
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <MyTable
      :tableList="tableList"
      :columns="columns"
      :total="Total"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="[]"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
      :customBtn="btnList"
      @custom="handleCustom"
    >
      <template v-slot:tabTop>
        <el-tabs
          v-model="queryParams.IsAnswer"
          @tab-click="getList"
          
        >
          <el-tab-pane label="未答复" name="0"></el-tab-pane>
          <el-tab-pane label="已答复" name="1"></el-tab-pane>
        </el-tabs>
        <!-- <el-button
            type=" primary" v-hasPermi="['DutyList:add']" icon="CirclePlusFilled" @click="handleAdd">添加区域</el-button> -->
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      title="添加作业"
      :formRef="formRef"
      :width="800"
      confirmText="提交作业"
      @confirm="handlePublishWord"
      :destroy="true"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        :label-width="80"
        ref="formRef"
        class="wid100"
      >
        <el-form-item label="作业要求">
          {{ publishDetail.Remark }}
        </el-form-item>
        <el-form-item label="作业附件">
          <FileUpload
            v-model:fileList="publishDetail.Files"
            :showBtn="false"
            :showSort="true"
          ></FileUpload>
        </el-form-item>
        <el-form-item label="作业说明" prop="Remark">
          <el-input
            v-model="formData.Remark"
            type="textarea"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <FileUpload v-model:fileList="fileList" :showFile="false"></FileUpload>
        <MyTable
          :tableList="fileList"
          :columns="fileColumns"
          v-model:page="page"
          :btnList="['delete']"
          @delete="handleDeleteFile"
          :toolbar="false"
        >
        </MyTable>
      </el-form>
    </MyDialog>
    <MyDialog
      v-model:show="showCourseWork"
      :title="title"
      :formRef="formRef"
      :width="800"
      :showFooter="false"
      @confirm="handlePublishWord"
    >
      <el-button type="primary" @click="handleDetailPublish(editInfo)"
        >提交作业</el-button
      >

      <div v-for="item in studentCourseWorkList" class="workInfo">
        <div class="flex jbetween acenter">
          <div class="publishTime flex acenter">
            <div>答复时间：</div>
            <div>
              <strong>{{ item.CreateTime }}</strong>
            </div>
          </div>
        </div>
        <div class="mgt10">
          答复说明：
          {{ item.Remark }}
        </div>
        <MyTable
          :tableList="item.Files"
          :columns="classFileColumns"
          :toolbar="false"
        ></MyTable>
        <div v-show="item.Comment">
          <div class="flex jend">
            <div><el-rate disabled :modelValue="item.Grade" allow-half /></div>
          </div>
          <div>教师评语：{{ item.Comment }}</div>
        </div>
      </div>
    </MyDialog>
  </div>
</template>

<script setup name="MyJob">
import { ref, getCurrentInstance, onMounted, computed } from "vue";
import useUserStore from "@/store/modules/user.js";
import {
  AddOrUpdateCourseAssign,
  DelCourseAssign,
  AddAnswerAssign,
  GradeAnswerAssign,
  GetCourseAssignList_Page,
  GetCourseAssignDetail,
  GetAnswerAssignList_Page,
  GetAssignSubmitDetail,
  GetAssignDetail,
} from "@/api/afterClass/index.js";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const tableList = ref([]);
const editInfo = ref({});
const Total = ref(0);
const tearchData = ref({});
const columns = ref([
  { label: "序号" },
  { label: "作业说明", prop: "Remark" },
  { label: "日期", prop: "DateDay" },
  { label: "上课时间/下课时间", prop: "StartAndEnd", width: 140 },
  { label: "班级", prop: "Name_Class" },
  { label: "场地", prop: "Name_Place" },
  { label: "课程", prop: "Name_Course" },
  { label: "授课老师", prop: "Name_Teacher" },
  { label: "操作", width: 120 },
]);
const fileColumns = ref([
  { label: "文件名称", prop: "Name", file: true },
  { label: "文件大小(kb)", prop: "SizeKb" },
  { label: "显示顺序", prop: "Sort", input: true },
  { label: "说明备注", prop: "Remark", input: true },
  { label: "操作", width: 100 },
]);
const classColumns = ref([
  { label: "班级学生数", prop: "StudentCount" },
  { label: "作业提交份数", prop: "SubmitCount" },
  { label: "操作", width: 100 },
]);
const classFileColumns = ref([
  { label: "文件名称", prop: "fileName", file: true },
  { label: "文件大小(kb)", prop: "SizeKb" },
  { label: "说明备注", prop: "Remark" },
]);
proxy.$formatKey(columns.value);
proxy.$formatKey(classColumns.value);
proxy.$formatKey(classFileColumns.value);
proxy.$formatKey(fileColumns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
});
const searchStatus = ref(true);
const queryParams = ref({
  Code: "",
  Name: "",
  NoPage: "", //如果传"true"，则返回全部数据不分页
  IsAnswer: 0,
});
const showCourseWork = ref(false);
const btnList = ref([{ name: "提交作业" }]);
const queryRef = ref();
const fileList = ref([]);
const show = ref(false);
const title = ref();
const courseDetailList = ref([]);
const formRef = ref();
const showStudentCourseDetail = ref(false);
const studentCourseWorkList = ref([]);
const publishDetail = ref({});
const rules = ref({
  Remark: [{ required: true, message: "请输入", trigger: "blur" }],
});
const formData = ref({});

onMounted(() => {
  getList();
});

async function getList() {
  switch (Number(queryParams.value?.IsAnswer)) {
    case 0:
      btnList.value = [{ name: "提交作业" }];
      break;
    case 1:
      btnList.value = [{ name: "查看作业" }];
      break;
  }
  try {
    let query = {
      ...queryParams.value,
      ...page.value,
      Student: queryParams.value.Student
        ? queryParams.value.Student
        : userInfo.value.ID,
    };

    let res = await GetAnswerAssignList_Page(query);
    res.data.List?.forEach((item) => {
      item.DateDay = item.DateDay?.slice(0, 10);
      item.StartAndEnd =
        item.StartTime?.slice(11, 16) + " -- " + item.EndTime?.slice(11, 16);
    });
    tableList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

async function getPublishDetail(id) {
  try {
    let res = await GetAssignDetail({ ID_Assign: id });
    publishDetail.value = res.data;
  } catch (error) {
    console.log(error);
  }
}

function handleDeleteFile(row) {
  fileList.value = fileList.value?.filter((item) => item.ID != row.ID);
}

async function handlePublishWord(val) {
  if (val) {
    try {
      let query = {
        ID_Assign: editInfo.value.ID_Assign,
        ...formData.value,
        Files: fileList.value?.map((item) => {
          return {
            FileID: item.ID,
            Sort: item.Sort,
            Remark: item.Remark,
          };
        }),
      };
      await AddAnswerAssign(query);
      proxy.$modal.msgSuccess("提交成功");
      getList();
      if (showCourseWork.value) {
        handleWorkDetail(editInfo.value);
      }
      show.value = false;
    } catch (error) {
      console.log(error);
    }
  }
}

async function handleWorkDetail(row) {
  try {
    let res = await GetAssignSubmitDetail({
      ID_Assign: row.ID_Assign,
      Student: userInfo.value.ID,
    });
    let list = res.data?.[0]?.Answers;
    list?.forEach((item) => {
      item.Files = item.Files?.map((file) => {
        return {
          ...file,
          SizeKb: Math.ceil(file.Size / 1024),
          fileName: file.Name + file.Suffix,
          Path: file.Path,
        };
      });
    });
    studentCourseWorkList.value = list;
  } catch (error) {
    console.log(error);
  }
}

function handleDetailPublish() {
  console.log(formData.value);
  formData.value = {};
  fileList.value = [];
  show.value = true;
}

async function handleCustom(row) {
  editInfo.value = row;
  await getPublishDetail(row.ID_Assign);
  switch (btnList.value[0]?.name) {
    case "提交作业":
      handleAdd(row);
      break;
    case "查看作业":
      title.value = "作业信息";
      await handleWorkDetail(row);
      showCourseWork.value = true;

      break;
  }
}

async function handleGetCourseDetail() {
  try {
    let res = await GetCourseAssignDetail({
      ID_Schedule: editInfo.value.ID_Schedule,
    });
    res.data?.forEach((item) => {
      item.Files = item?.Files?.map((file) => {
        return {
          ...file,
          SizeKb: Math.ceil(file.Size / 1024),
          fileName: file.Name + file.Suffix,
          Name: file.Name + file.Suffix,
          ID: file.FileID,
          Path: file.Path,
        };
      });
    });
    console.log(res.data);
    courseDetailList.value = res.data;
  } catch (error) {
    console.log(error);
  }
}

function handleEdit(row) {
  title.value = "修改";
  formData.value = {};
  show.value = true;
}
async function handleDelete(row) {}
async function handleAdd() {
  try {
    let query = {};
    tearchData.value = {};
    formData.value = {};
    title.value = "提交作业";
    fileList.value = [];
    show.value = true;
  } catch (error) {
    console.log(error);
  }
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: "",
    Name: "",
    NoPage: "",
    IsAnswer: 0,
  };
  handleQuery();
}
</script>

<style lang="scss" scoped>
.workInfo {
  border: 1px solid #ddd;
  padding: 10px;
  margin-top: 10px;
  border-radius: 6px;
}
</style>
